package com.cskaoyan.search.controller;

import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.mall.commons.result.ResponseData;
import com.cskaoyan.mall.commons.result.ResponseUtil;
import com.cskaoyan.search.consts.SearchRetCode;
import com.cskaoyan.search.exception.ControllerExceptionHandler;
import com.cskaoyan.search.form.SearchRequest;
import com.cskaoyan.search.dto.SearchResponse;
import com.cskaoyan.search.service.InitDataService;
import com.cskaoyan.search.service.ProductSearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;


/**
 * 商城全部商品搜索和热门推荐
 */
@RestController
@RequestMapping("/shopping")
public class SearchController {

    @Autowired
    private ProductSearchService productSearchService;

    @Autowired
    private InitDataService initDataService;

    /**
     * 精准搜索
     * @param request
     * @return
     */
    @PostMapping("/search")
    public ResponseData<SearchResponse> searchProduct(@Validated @RequestBody SearchRequest request) {
        SearchResponse response = productSearchService.search(request);
        return new ResponseUtil().setData(response);
    }

    /**
     * 搜索商品
     * @param key
     * @return
     */
    @GetMapping("/search/{key}")
    public ResponseData search(@PathVariable("key") String key) {
        SearchRequest searchRequest = new SearchRequest();
        searchRequest.setKey(key);
        searchRequest.setPage(0);
        searchRequest.setSize(10);
        SearchResponse searchResponse = null;
        try {
            searchResponse = productSearchService.fuzzySearch(searchRequest);
            return new ResponseUtil().setData(searchResponse.getData());
        } catch (IOException e) {
            e.printStackTrace();
            throw new BizException(SearchRetCode.FAILED.getCode(),SearchRetCode.FAILED.getMsg());
        }

    }

    @GetMapping("/search/init")
    public ResponseData init() {

        initDataService.initItems();
        return new ResponseUtil().setData(null);

    }
}
